package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.Get;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        //1. 判断添加的菜品 或 套餐
        Long dishId = shoppingCart.getDishId();
        // 获取登录用户信息
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        if (dishId != null) {
            // 当前添加是菜品
            lqw.eq(ShoppingCart::getDishId, dishId);
        } else {
            // 当前添加是套餐
            lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        // 查询
        ShoppingCart cart = shoppingCartService.getOne(lqw);
        // 判断购物车是否已有该菜品/套餐
        if (cart != null) {
            // 购物车已有该菜品/套餐
            cart.setNumber(cart.getNumber() + 1);  // 数量+1
            shoppingCartService.updateById(cart);
        } else {
            // 购物车没有该菜品
            shoppingCart.setNumber(1); // 默认数量1
            shoppingCart.setUserId(userId);  // 设置所有用户
            shoppingCartService.save(shoppingCart);
            cart = shoppingCart;
        }
        return R.success(cart);
    }

    /**
     * 查询购物车
     *
     * @return
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> list() {
        //1. 条件构建器
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        lqw.orderByDesc(ShoppingCart::getCreateTime);

        //2. 查询
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        return R.success(list);
    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("clean")
    public R<String> clean() {
        //1. 条件构建器
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        //2. 删除
        shoppingCartService.remove(lqw);
        return R.success("清空购物车成功");
    }
}
